package com.hzqy.web.filter;

import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.commons.utils.SystemKeyUtil;
import com.hzqy.web.login.*;
import com.hzqy.web.vo.system.SysWarnVo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class LoginFilter implements Filter {
	private static final Log LOG = LogFactory.getLog(LoginFilter.class);
	private String startTime = "";
	private String endTime = "";
	private String privateKey = "";//个人密钥
	private String systemKey = "";//本地存储的系统密钥
	private String generatedsystemKey = "";//生成的系统密钥
	private static final String GO_COMMON_AB = "go_common_ab";
	private static final String PLATFORM = "platform"; 
	
	public void init(FilterConfig config) throws ServletException {
		ServletContext servletContext = config.getServletContext();
		startTime = servletContext.getInitParameter("startTime");
		endTime = servletContext.getInitParameter("endTime");
		privateKey = servletContext.getInitParameter("privateKey");
		systemKey = servletContext.getInitParameter("systemKey");
		generatedsystemKey = SystemKeyUtil.getSysKey(privateKey,startTime,endTime);
		boolean isTrue = SystemKeyUtil.complianceKeyAndDBTime(startTime, endTime, generatedsystemKey, systemKey,servletContext);
		if(isTrue){
			LOG.debug("=========================================================");
		}else{
			LOG.debug("---------------------------------------------------------");
			try {
				Thread.sleep(1000000000);
			} catch (InterruptedException e) {
				LOG.error(e);
			}
		}
		LOG.debug("iTV业务登录解析EPG_INFO参数过滤器启动...");
	}
	
	public void destroy() {}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = ((HttpServletRequest)request);
		HttpServletResponse resp = ((HttpServletResponse)response);
		HttpSession session = req.getSession();
		String uri = req.getRequestURI();
		ServletContext servletContext= session.getServletContext();
		boolean isTrue = SystemKeyUtil.complianceKeyAndDBTime(startTime, endTime, generatedsystemKey, systemKey,servletContext);
		if(isTrue){
			//LOG.debug("=========================================================");
		}else{
			LOG.debug("---------------------------------------------------------");
			try {
				Thread.sleep(1000000000);
			} catch (InterruptedException e) {
				LOG.error(e);
			}
		}
		
		
		WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
		boolean releaseIsTrue = false;//是否放通
		String commonSwitch = SystemConfigUtils.getSysConfig(GO_COMMON_AB);//查询一键放通是否开启 1：不开启  2：开启
		if("2".equals(commonSwitch)){
			releaseIsTrue = true;
			session.setAttribute("platform", SystemConfigUtils.getSysConfig(PLATFORM));//平台 区分酒店和校园，行业
		}
		
		if(uri.endsWith("warn.jsp")||uri.endsWith("demo.jsp") || uri.endsWith("error.jsp") || uri.endsWith("service_authentication.jsp") || uri.endsWith("release.jsp") || uri.endsWith("clear_cache.do")
				|| uri.endsWith("marketing.do") || uri.endsWith("marketingEPG.do") || uri.endsWith("service_order.jsp") || uri.endsWith("service_order_back.jsp") || uri.endsWith("service.jsp")|| uri.endsWith("/integralBF/clear_voteCache.do")
				|| uri.endsWith(".jpg") || uri.endsWith(".gif") || uri.endsWith(".png") || (uri.indexOf("/PIC/")>=0&&!(uri.indexOf("/PIC/model/")>=0))
				|| uri.indexOf("/monitor/") >= 0 || uri.endsWith("not_bind_model.jsp") ||uri.endsWith("proving.js")
						|| uri.endsWith(".jad")|| uri.endsWith(".mp4")|| uri.endsWith(".mp3")|| uri.endsWith(".jar")//|| uri.indexOf("/tv_proving/")>=0 
				|| uri.indexOf("/js/")>=0 || uri.indexOf("/css/")>=0 || (uri.indexOf("/mobile_tv_wchat_service/")>=0)
				|| uri.indexOf("/service/")>=0 || uri.indexOf("/interface/") >= 0 || uri.indexOf("/itf/") >= 0  || uri.indexOf("/insertCoupon.do")>=0 || uri.endsWith("/wchat/connect.do") || uri.endsWith(".txt") || uri.indexOf("/mobile/")>=0 ||uri.indexOf("/external/")>=0 ||uri.indexOf("msykAccountBinding.do") >= 0
				|| uri.indexOf("/third_wechat_payment/")  >= 0 || uri.indexOf("receiveOrder.do")  >= 0  || uri.indexOf("receive.do")  >= 0
				||uri.indexOf("/mclz/")>=0) { //不过滤的页面
				chain.doFilter(request, response);
		}else{
				//WebApplicationContext webApplicationContext = WebApplicationContextUtils.getWebApplicationContext(servletContext);
				//SysWarnServiceBeen sysWarnServiceBeen = (SysWarnServiceBeen)webApplicationContext.getBean("sysWarnServiceBeen"); //获得springmvc注入的对象
				SysWarnVo sysWarnVo=null; //sysWarnServiceBeen.selectWarnVoInfo();
				if(!releaseIsTrue//放通判断
						&&sysWarnVo!=null&&sysWarnVo.getF_sw_id()>0//公告存在数据
						&&!(sysWarnVo.getF_sw_id()+"|"+sysWarnVo.getF_sw_update()).equals(String.valueOf(session.getAttribute("SYS_WARN_FLAG")))){//存在公告对象
					//判断公告是否为最新
					String requestData="";
					if(req.getQueryString()!=null){
						requestData="?"+req.getQueryString();
					}
					session.setAttribute("SYS_WARN_URL", req.getRequestURI()+requestData);
					session.setAttribute("SYS_WARN_FLAG",sysWarnVo.getF_sw_id()+"|"+sysWarnVo.getF_sw_update());
					session.setAttribute("SYS_WARN_PIC",sysWarnVo.getF_cp_url());
					resp.sendRedirect(req.getContextPath()+"/commons/warn.jsp"); //重定向到错误页面
				}else{
				String epg_info = req.getParameter("epg_info");
				Object serverIdObj = session.getAttribute(SessionKey.SESSION_SERVERID);
				//serverIdObj为空,有可能是用户第一次登录
				//可能是SESSION超时
				//也有可能是EPG带来的参数有错误!
				if(serverIdObj == null  || (epg_info!=null&&epg_info.trim().length()>0)) { 
					if(epg_info == null || epg_info.trim().length() <= 0) { //EPG参数错误,没有取到,直接进入登录失败页面
						//LOG.error("EPG参数错误,没有取到,直接进入登录失败页面...");
						resp.sendRedirect(req.getContextPath()+"/commons/error.jsp"); //重定向到错误页面
					} else { //用户第一次登录,开始解析EPG带来的参数
						//LOG.debug("用户第一次登录,开始解析EPG带来的参数...");
						//该Observable是倒序通知观察者
						EpgInfoParse loginParse = new EpgInfoParse();
						loginParse.addObserver(new UserInfoSession(req));
						loginParse.addObserver(new AreaSession(req));
						loginParse.addObserver(new ResolutionSession(req));
						loginParse.addObserver(new PartnerIDSession(req));
						loginParse.addObserver(new RecsourceSession(req));
						loginParse.addObserver(new JumpUrlSession(req));
						loginParse.addObserver(new EpgInfoSession(req));
						//loginParse.addObserver(new RemoveSession(req));
						try {
							loginParse.loginParse(session, epg_info);
							if(releaseIsTrue){
								LOG.debug("重定向到放通页面");
								resp.sendRedirect(req.getContextPath()+"/commons/release.jsp"); //重定向到放通页面
							}else{
								chain.doFilter(request, response);
							}
						} catch (Exception e) {
							LOG.error("解析EPG_INFO出错！",e);
							resp.sendRedirect(req.getContextPath()+"/commons/error.jsp"); //重定向到错误页面
						} finally {
							loginParse.deleteObservers();
						}
					}
				} else { //session不为空,说明用户已经成功登录的
					if(releaseIsTrue){
						LOG.debug("重定向到放通页面");
						resp.sendRedirect(req.getContextPath()+"/commons/release.jsp"); //重定向到放通页面
					}else{
						chain.doFilter(request, response);
					}
				}
			}
		}
		
	}
}




